// 防抖 如果有新的进来，清除旧的，执行新的
export function shake(fn, wait) {
  let timer = null;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(fn, wait);
  };
}

// 节流 如果有的新的就来也不用管，等到执行完旧的，再执行新的
export function throttle(fn, wait) {
  let time = Date.now();
  return function (...arg) {
    let newTime = Date.now();
    if (newTime - time >= wait) {
      fn.apply(this, arg);
      time = newTime;
    }
  };
}
// 处理数据为树模式
export function toTree(data) {
  let result = [];
  if (!Array.isArray(data)) {
    return result;
  }
  data.forEach((item) => {
    delete item.children;
  });
  let map = {};
  data.forEach((item) => {
    map[item.name] = item;
  });
  data.forEach((item) => {
    let parent = map[item.parentName];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
}

// 数字转K、M结尾 | 1000 = 1k  100000 = 1M
export const numberToKM = (num) => {
  if (num < 1000) return num;
  let transform = [100, "K"];
  if (num >= 1000000) transform = [100000, "M"];
  return Math.floor(num / transform[0]) / 10 + transform[1];
};

// 将CSV数据转为JSON格式
export function csvToJson(data){
  var lines = data.split("\n");
  var headers = lines[0].split(",");
  var jsonArray = [];
  
  for (var i = 1; i < lines.length; i++) {
    var currentLine = lines[i].split(",");
    var obj = {};
  
    for (var j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentLine[j];
    }
    jsonArray.push(obj);
  }
  return jsonArray
}

// 引入本地图片
export const requireImg = (imgName) => {
  return new URL(`/src/assets/image/${imgName}`, import.meta.url).href;
}

// 设置宽高比例缩放
export const setScale = (containerDom) => {
  // 1. 设计稿的宽高、文档的宽高
  const designWidth = 4352
  const designHeight = 1536
  const nowWidth = document.documentElement.clientWidth // 文档宽  // window.screen.width 屏幕宽
  const nowHeight = document.documentElement.clientHeight
  // 2. 设计图的宽高比例、文档的宽高比例
  const designRatio = designWidth/designHeight
  const nowRatio = nowWidth/nowHeight
  // 3. 最终页面放置的容器 containerDom
  // 4. 判断文档的宽高比是否小于设计稿的宽高比：小于 按宽度缩放 大于 按高度缩放
  const scale = nowRatio < designRatio ? nowWidth / designWidth : nowHeight / designHeight
  containerDom.style.transform = `scale(${scale}) translate(-50%,-50%)`
}